package com.rainy.cloud.gateway.route.repository;

import com.google.gson.Gson;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author user
 */
@Component
public class RedisRouteLoadRepository {

    public static final String  GATEWAY_ROUTES = "gateway:routes";

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    public Flux<RouteDefinition> getRouteDefinitions() {
        List<RouteDefinition> routeDefinitions = new ArrayList<>();
        redisTemplate.opsForHash().values(GATEWAY_ROUTES).stream().forEach(routeDefinition -> {
            Gson gson = new Gson();
            routeDefinitions.add(gson.fromJson(routeDefinition.toString(), RouteDefinition.class));
        });
        return Flux.fromIterable(routeDefinitions);
    }

    public void save(RouteDefinition routeDefinition) {
        Gson gson = new Gson();
        redisTemplate.opsForHash().put(GATEWAY_ROUTES, routeDefinition.getId(), gson.toJson(routeDefinition));
    }

    public void delete(String id) {
        if (redisTemplate.opsForHash().hasKey(GATEWAY_ROUTES, id)) {
            redisTemplate.opsForHash().delete(GATEWAY_ROUTES, id);
        }
    }
}
